require('./Myslide.styl');
const { Boxs, Icon, Badge } = SaltUI;
const { HBox, Box } = Boxs;
var classNames = require('classnames/bind');
import { Control } from 'react-keeper'
class Myslide extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            isPan: false
        };
        this.handleClick = this.handleClick.bind(this);
        this.handleClickBtn = this.handleClickBtn.bind(this);
        this.prevent = this.prevent.bind(this);
    }
    //点击的逻辑
    handleClick() {
        let t = this;
        if (this.stage.offsetLeft == -80) {
            this.clear();
            return;
        }
        if (t.props.badge) {
            t.props.cb && t.props.cb(t.props.notice_id)
        }
        if (t.props.refreshing) return;
        let subcontent = this.props.data.content[this.props.data.content.length - 1].subcontent;
        if (subcontent != "待审批")
            this.props.tool = !this.props.tool;
   
        Control.go('/home/workplan/pending/detail/' + this.props.tool, { process_id: this.props.data.process_id, origin: this.props.origin });
    }
    //删除按钮
    handleClickBtn() {
        this.clear();
        // this.props.cb(index, showbtn);
        let t = this;
        console.log(t.props)

        t.props.delete && t.props.delete(t.props.notice_id);
    }
    render() {
        let t = this;
        let id = `wrap${this.props.index}`
        var styles = {
            msg: 'msg',
            workplan: 'workplan-manage'
        };
        var cx = classNames.bind(styles);
        if (this.props.className) {
            for (let key in styles) {
                if (this.props.className.includes(styles[key])) {
                    var obj = {};
                    Object.assign(obj, { [`${key}`]: true });
                }
            }
        }
        if (JSON.stringify(obj) == "{}") {
            var className = cx('listitem', this.props.className);
        } else {
            var className = cx('listitem', obj);
        }
        return (
            <div className="myslide-group-list-item" >
                <div id={id} className="myslide-list-wrap" onClick={this.handleClick}>
                    <div className="myslide-list-text-content">
                        <div className={classNames("myslide-item-title myslide-omit", className)}>
                            <HBox className={classNames({ 'head': true })} vAlign="center">
                                {t.props.data.badge && <Box>
                                    <Badge dot >
                                        <div></div>
                                    </Badge>
                                </Box>}
                                <Box flex={2} >{t.props.data.title}</Box>
                                <Box flex={1}>
                                    <h4>{t.props.data.subtitle && t.props.data.subtitle.split(" ")[0]}</h4>
                                </Box>
                            </HBox>
                            {t.props.data.content && t.props.data.content.map((item, index) => {
                                return (<HBox vAlign="center" className={classNames({ 'content': true })} >
                                    <Box className={classNames({ contentColor: item.className == "green" })}>{item.subcontent}</Box>
                                    <Box>{item.subcontent && item.unitcontent && "："}{typeof item.unitcontent == "number" ? new Date(item.unitcontent).toLocaleDateString() : item.unitcontent}</Box>
                                </HBox>
                                )
                            })}
                        </div>
                    </div>
                </div>
                <div className="myslide-list-behind" onClick={() => { t.handleClickBtn() }}>
                    <div className="myslide-list-delete-btn">
                        <span className="myslide-list-delete-btn-text">{t.props.btnName}</span>
                    </div>
                </div>
            </div>
        );
    }

    componentWillMount() {
    }

    componentDidMount() {

        let t = this;
        let id = `wrap${this.props.index}`;
        //获取节点
        var stage = document.getElementById(id);
        //创建手势管理者
        var mc = new Hammer.Manager(stage);
        //创建手势
        var pan = new Hammer.Pan({ direction: Hammer.DIRECTION_LEFT | Hammer.DIRECTION_RIGHT });
        mc.add([pan]);
        this.clear = () => {
            stage.style.left = '0';
            stage.style.transition = 'transition-duration:.2s';
        }
        this.stage = stage;
        t.prevent();
        t.judge = false;
        // listen to events...
        mc.on("panleft panright", function (e) {
            if (e.type == 'panleft' || e.type == 'panright') {
                // console.log("t="+!t.judge)   
                // if(!t.judge){
                //     PreventGhostClick(t.stage);
                //     t.judge = true;              
                // }
                PreventGhostClick(t.stage);
            }
            if ((Math.abs(e.angle) <= 180 && Math.abs(e.angle) > 165) || Math.abs(e.angle) < 15) {

                if ('panleft' == e.type) {
                    if (e.isFinal) {
                        if (e.distance >= 10) {
                            stage.style.left = '-80px';
                            stage.style.transition = 'transition-duration:.3s';
                        } else {
                            stage.style.left = '-80px';
                            stage.style.transition = 'transition-duration:.1s';
                        }

                    } else {
                        if (e.distance <= 70) {
                            stage.style.left = e.deltaX + 'px';
                        } else {
                            stage.style.left = '-80px';
                            stage.style.transition = 'transition-duration:.1s';
                        }
                    }
                }
                if ('panright' == e.type) {
                    stage.style.left = '0';
                    stage.style.transition = 'transition-duration:.3s';
                }
            }
            if (e.isFinal) {
                t.timeoutID = setTimeout(() => {
                    remove(t);
                }, 1300);
            }
        });

    }
    prevent() {


        (function (window, document, exportName) {
            var coordinates = [];
            var threshold = 25;
            var timeout = 2500;

            // no touch support
            if (!("ontouchstart" in window)) {
                window[exportName] = function () { };
                return;
            }

            /**
             * prevent clicks if they're in a registered XY region
             * @param {MouseEvent} ev
             */
            function preventGhostClick(ev) {
                for (var i = 0; i < coordinates.length; i++) {
                    var x = coordinates[i][0];
                    var y = coordinates[i][1];
                    // within the range, so prevent the click
                    if (Math.abs(ev.clientX - x) < threshold && Math.abs(ev.clientY - y) < threshold) {
                        ev.stopPropagation();
                        ev.preventDefault();
                        break;
                    }
                }
            }

            /**
             * reset the coordinates array
             */
            function resetCoordinates() {
                coordinates = [];
            }

            /**
             * remove the first coordinates set from the array
             */
            function popCoordinates() {
                coordinates.splice(0, 1);
            }

            /**
             * if it is an final touchend, we want to register it's place
             * @param {TouchEvent} ev
             */
            function registerCoordinates(ev) {
                // touchend is triggered on every releasing finger
                // changed touches always contain the removed touches on a touchend
                // the touches object might contain these also at some browsers (firefox os)
                // so touches - changedTouches will be 0 or lower, like -1, on the final touchend
                if (ev.touches.length - ev.changedTouches.length <= 0) {
                    var touch = ev.changedTouches[0];
                    coordinates.push([touch.clientX, touch.clientY]);
                    setTimeout(popCoordinates, timeout);
                }
            }
            function remove(t) {
                let timeoutID = t.timeoutID;
                document.removeEventListener("click", preventGhostClick, true);
                if (timeoutID) {
                    clearTimeout(timeoutID)
                }
                console.log("remove=" + t.judge)
                t.judge = false;
            }
            /**
             * prevent click events for the given element
             * @param {EventTarget} el
             */
            window[exportName] = function (el) {
                el.addEventListener("touchstart", resetCoordinates, true);
                el.addEventListener("touchend", registerCoordinates, true);
                window.remove = remove;
            };

            document.addEventListener("click", preventGhostClick, true);
        })(window, document, 'PreventGhostClick');
    }
    componentWillReceiveProps(nextProps) {
    }

    shouldComponentUpdate(nextProps, nextState) {
        return true;
    }

    componentWillUpdate(nextProps, nextState) {
    }

    componentDidUpdate(prevProps, prevState) {
    }

    componentWillUnmount() {
    }
}

module.exports = Myslide;
